package com.knowswift.security.handler.success;

import com.knowswift.common.utils.GetUUIDUtils;
import com.knowswift.common.utils.JwtTokenUtils;
import com.knowswift.common.utils.WrappedBeanCopier;
import com.knowswift.security.account.User;
import com.knowswift.security.account.UserService;
import com.knowswift.security.account.UserVO;
import com.knowswift.security.handler.AbstractLoginSuccessHandler;
import com.knowswift.security.param.MiniLoginParam;
import com.knowswift.security.token.MiniProgramAuthenticationToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @company https://www.knowswift.com
 */
@Component
public class UserMiniProgramLoginSuccessHandler extends AbstractLoginSuccessHandler {

    @Resource
    private UserService userService;
//
//    @Resource
//    private OfficialSubscriberService officialSubscriberService;

    @Override
    public Object preAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        MiniProgramAuthenticationToken miniProgramAuthenticationToken = (MiniProgramAuthenticationToken) authentication;
        MiniLoginParam miniLoginParam = miniProgramAuthenticationToken.getMiniLoginParam();
        User user = (User) authentication.getPrincipal();
        if (StringUtils.isBlank(user.getNickname())) {
            user.setNickname("用户" + GetUUIDUtils.getUUIDBits(8));
        }
        Map<String, Object> claims = new HashMap<>();
        user.setAppTokenVersion(user.getAppTokenVersion() + 1);
//        if (!StringUtils.isBlank(user.getWechatUnionId())) {
//            OfficialSubscriber one = officialSubscriberService.getOne(new LambdaQueryWrapper<OfficialSubscriber>()
//                    .eq(OfficialSubscriber::getUnionId, user.getUnionId()));
//            if (one != null) {
//                user.setOfficialOpenId(one.getOfficialOpenId());
//                user.setSubscribed(true);
//            }
//        }

        userService.saveOrUpdate(user);
        claims.put("tokenVersion", user.getAppTokenVersion());
        String token = JwtTokenUtils.generateToken(claims, user.getId());
        UserVO userVo = WrappedBeanCopier.copyProperties(user, UserVO.class);
        userVo.setToken(token);
        return userVo;
    }
}